package cn.gzjp.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;

public class BaiduAPI {
	
	 /** 
     * 计算两点之间距离 
     * @param 
     * @param 
     * @return 千米
     */  
    public static String getDistance(Double longitude,Double latitude,Double addressX, Double addressY){ 
        double lon1 = (Math.PI/180)*longitude;  
        double lon2 = (Math.PI/180)*addressX;//经度  
  
        double lat1 = (Math.PI/180)*latitude;  
        double lat2 = (Math.PI/180)*addressY;//维度  
  
        //地球半径  
        double R = 6371;  
  
        //两点间距离 km，如果想要米的话，结果*1000就可以了  
        double d =  Math.acos(Math.sin(lat1)*Math.sin(lat2)+Math.cos(lat1)*Math.cos(lat2)*Math.cos(lon2-lon1))*R;  
/*        d=d*1000;*/  
        DecimalFormat df=new DecimalFormat("0.00");  
        return  df.format(d)+"km";  
    }  
    
    /*
	 * 获取经纬度
	 */
	public static Map<String, Double> getLngAndLat(String address) {
		Map<String, Double> map = new HashMap<String, Double>();
		String url = "http://api.map.baidu.com/geocoder/v2/?address=" + address
				+ "&output=json&ak=wPGq8F8k4dvVcm3fXyE4giPF";

		String json = loadJSON(url);
		JSONObject obj = JSONObject.parseObject(json);
		if (obj.get("status").toString().equals("0")) {
			double lng = obj.getJSONObject("result").getJSONObject("location").getDouble("lng");
			double lat = obj.getJSONObject("result").getJSONObject("location").getDouble("lat");
			map.put("lng", lng);
			map.put("lat", lat);
			 System.out.println("经度："+lng+"---纬度："+lat);
		} else {
			// System.out.println("未找到相匹配的经纬度！");
		}
		return map;
	}

	/*
	 * 请求地图服务器获取经纬度
	 */
	public static String loadJSON(String url) {
		StringBuilder json = new StringBuilder();
		try {
			URL oracle = new URL(url);
			URLConnection yc = oracle.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
			String inputLine = null;
			while ((inputLine = in.readLine()) != null) {
				json.append(inputLine);
			}
			in.close();
		} catch (MalformedURLException e) {
		} catch (IOException e) {
		}
		return json.toString();
	}

	public static void main(String[] args) {

		Map<String, Double> map = BaiduAPI.getLngAndLat("广州市科学城神舟路9号");
		
		double addressX=113.43819763012672;
		double addressY=23.175435090650247;
		double longitude = 113.307;
		double latitude= 23.150;
		System.out.println(BaiduAPI.getDistance(longitude, latitude, addressX, addressY));
	}

}
